#include "friendmodel.hpp"
#include "db.hpp"
#include <muduo/base/Logging.h>

using namespace std;

static std::string server = "127.0.0.1";
static std::string dbuser = "root";
static std::string dbpwd = "123456";
static std::string dbname = "chat";

void FriendModel::insert(int userid, int friendid)
{
    char sql[1024] = { 0 };
    sprintf(sql, "insert into friend values('%d', '%d')", userid, friendid);

    MySQL mysql;
    if (mysql.connect(server, dbuser, dbpwd, dbname)) {
        mysql.update(sql);
    }
}

std::vector<User> FriendModel::query(int userid)
{
    char sql[1024] = { 0 };
    MYSQL_RES *res;
    MySQL mysql;
    MYSQL_ROW row;
    vector<User> users;

    do {
        res = nullptr;
        row = nullptr;
        sprintf(sql, "select a.id, a.name, a.state from user a inner join friend b on b.friendid = a.id where b.userid = %d", userid);
        if (mysql.connect(server, dbuser, dbpwd, dbname)) {
            res = mysql.query(sql);
            if (!res) {
                LOG_ERROR << "failed to query user " << userid;
                break;
            }

            while (row = mysql_fetch_row(res)) {
                User user;
                user.setId(atoi(row[0]));
                user.setName(row[1]);
                user.setState(row[2]);
                users.push_back(user);
            }

        }
    } while (0);
    if (res) {
        mysql_free_result(res);
    }
 
    return users;
}